/*
 * Course:    CS 590 Web Services
 * Semseter:  Spring 2009
 * Professor: Sedlemeyer
 * Project:   CHEAT (Code Help Educational Assignment Tool)
 * Due Date:  May 1, 2009
 * Team:      Sarcasm
 *            (Baker, Jason; Mitchell, Robin; Shie, Keith)
 */
package cheat.mail;

import com.sun.mail.smtp.SMTPTransport;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 * Message driven bean which processes queued requests to send mail.
 *
 * @author Keith Shie
 */
@MessageDriven(mappedName = "jms/mail", activationConfig = {
  @ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-acknowledge"),
  @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue")
})
public class MailMessageBean implements MessageListener {

  final private String protocol = "smtp";
  final private String host = "smtp.gmail.com";
  final private int port = 587;
  final private String user = "cs590.cheat@gmail.com";
  final private String password = "cs590Ch3at";

  private static Logger logger = Logger.getLogger(MailMessageBean.class.getPackage().getName());


  private void sendReport( String recipient, String title, String message ) throws MessagingException, IOException {
    final Properties props = System.getProperties();

    final boolean debug = false;
    final String from = user;
    final String to = "cs590.cheat@gmail.com";//recipient;
    final String cc = null;
    final String bcc = null;
    final String mailer = "InvestmentClub";
    final DateFormat dtFmt = new SimpleDateFormat( "MMM yyyy" );

    final StringBuffer subject = new StringBuffer( "CHEAT: " );
    subject.append( title );

    if (host != null) {
      props.put( "mail.smtp.host", host );
    }

    if (port != -1) {
      props.put( "mail.smtp.port", String.valueOf( port ) );
    }

    props.put( "mail.smtp.auth", "true" );
    // Get a Session object
    final Session session = Session.getInstance( props, null );
    if (debug) {
      session.setDebug( true );
    }
    final Transport tr = session.getTransport( protocol );
    SMTPTransport str = (SMTPTransport) tr;
    str.setStartTLS( true );
    tr.connect( host, user, password );


    // construct the message
    final javax.mail.Message msg = new MimeMessage( session );
    if (from != null) {
//        msg.setFrom(new InternetAddress(from));
      msg.setFrom( new InternetAddress( from, "CHEAT" ) );
    } else {
      msg.setFrom();
    }

    msg.setRecipients( javax.mail.Message.RecipientType.TO, InternetAddress.parse( to, false ) );
    if (cc != null) {
      msg.setRecipients( javax.mail.Message.RecipientType.CC, InternetAddress.parse( cc, false ) );
    }
    if (bcc != null) {
      msg.setRecipients( javax.mail.Message.RecipientType.BCC, InternetAddress.parse( bcc, false ) );
    }

    msg.setSubject( subject.toString() );

    final String text = "Testing..."; //collect(in);

//    if (file != null) {
//      // Attach the specified file.
//      // We need a multipart message to hold the attachment.
//      final MimeBodyPart mbp1 = new MimeBodyPart();
//      mbp1.setText(text);
//      final MimeBodyPart mbp2 = new MimeBodyPart();
//      mbp2.attachFile(file);
//      final MimeMultipart mp = new MimeMultipart();
//      mp.addBodyPart(mbp1);
//      mp.addBodyPart(mbp2);
//      msg.setContent(mp);
//    }

    msg.setHeader( "X-Mailer", mailer );
    msg.setSentDate( new Date() );
    msg.setText( message );

    // send the thing off
    msg.saveChanges();      // don't forget this
    tr.sendMessage( msg, msg.getAllRecipients() );
    tr.close();

    logger.fine( "\nMail was sent successfully." );
  }


  /**
   * Process one message from the message queue.
   *
   * <p>Messages placed onto this queue must be of type MapMessage.</p>
   *
   * <p>Each message must have the following properties:</p>
   *
   * <ul><li>recipient</li>
   * <li>title</li>
   * <li>message</li>
   * </ul>
   *
   * @param message
   */
  public void onMessage( Message message ) {
    logger.finer( "MailMessageBean: onMessage()" );
    MapMessage mm = (MapMessage) message;
    try {
      final String recipient = mm.getString( "recipient" );
      final String title = mm.getString( "title" );
      final String msg = mm.getString( "message" );

      logger.fine( "recipient: " + recipient + ", message: " + msg );
//      if (false) {
        sendReport( recipient, title, msg );
//      }
    } catch (MessagingException ex) {
      logger.log( Level.SEVERE, ex.getMessage() );
    } catch (IOException ex) {
      logger.log( Level.SEVERE, ex.getMessage() );
    } catch (JMSException ex) {
      logger.log( Level.SEVERE, ex.getMessage() );
    }
  }
}
